package com.fenghongzhang.day006;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageLoader {

    private static final String TAG = "ImageLoader";
    private static ImageLoader imagerLoader;

    private ExecutorService executorService;
    private LruCache<String,Bitmap> cache;
    private ImageLoader(){
        executorService = Executors.newSingleThreadExecutor();
        int i  =(int) (Runtime.getRuntime().maxMemory() / 10);
        cache = new LruCache<String,Bitmap>(i){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }
    public static ImageLoader getInstance(){
        if (imagerLoader == null){
            synchronized (ImageLoader.class){
                if(imagerLoader == null){
                    imagerLoader = new ImageLoader();
                }
            }
        }
        return imagerLoader;
    }

    //下载和缓存逻辑
    public void loading(final String url){
        //图片名称
//        http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg
        final String name = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."));
        //1内存
        Bitmap bitmap = cache.get(name);
        if(bitmap !=null){
            //用
            myListener.load(bitmap);
            Log.i(TAG, "loading: 内存读取");
        }else{
            //内存没有.sd读取
            //还没有创建文件.
///storage/emulated/0/fengimage/8289.jpg
            File path = new File(Environment.getExternalStorageDirectory()+File.separator+"fengimage"+File.separator);
            Bitmap bitmapsd = null;
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(path, name));
                bitmapsd = BitmapFactory.decodeStream(fileInputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            if(bitmapsd != null){
                Log.i(TAG, "loading: 从sd读取");
//               //sd
                myListener.load(bitmapsd);
                //放入到内存
                cache.put(name,bitmapsd);
            }else{
                //3 网络上
            //主
            final Handler handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    Bitmap bitmap1 = (Bitmap) msg.obj;
                    myListener.load(bitmap1);
                }
            };

               executorService.execute(new Runnable() {
                   @Override
                   public void run() {
                       try {
                           Log.i(TAG, "run: 从网络下载");
                           URL url1 = new URL(url);
                           HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
                           if (urlConnection.getResponseCode() == 200){
                               InputStream inputStream = urlConnection.getInputStream();
                               Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);

                               //存sd
                               //sd存在.
                               saveToSD(bitmap1, name);

                               //存内存.
                               cache.put(name,bitmap1);

                               Message obtain = Message.obtain();
                               obtain.obj = bitmap1;
                               handler.sendMessage(obtain);
//                               myListener.load(bitmap1);


                           }else{
                               Log.i(TAG, "run: 没网");
                           }
                       } catch (MalformedURLException e) {
                           e.printStackTrace();
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }
               });



            }
        }

    }

    //c + a + m
    private void saveToSD(Bitmap bitmap1, String name) throws FileNotFoundException {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//                                   /storage/emulated/0/fengimage/
            File path = new File(Environment.getExternalStorageDirectory()+File.separator+"fengimage"+File.separator);
            if(!path.exists()){
                path.mkdirs();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(new File(path, name));
            bitmap1.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);

        }else{
            Log.i(TAG, "run: 没有sd卡");
        }
    }

    public interface MyListener{
        void load(Bitmap bitmap);
    }

    private MyListener myListener; //空

    public void setMyListener(MyListener myListener) {
        this.myListener = myListener;
    }
}
